package com.camel.chart.utils.entity;

import com.camel.chart.enums.MsgTypeEnum;
import lombok.Data;

import java.io.*;
import java.util.Arrays;
import java.util.UUID;

@Data
public class Msg implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 消息类型
     */
    private MsgTypeEnum type;

    /**
     * 消息
     */
    private Object msg;

    /**
     * 发消息IP
     */
    private String originAddr;

    /**
     * 接收IP
     */
    private String targetAddr;


    /**
     * 时间
     */
    private String dataTime;

    /**
     * ID
     */
    private String uuid;

    /**
     * 是否是左边
     */
    private boolean left;

    public Msg() {
        this.setLeft(false);
    }

    public static Msg FILE_REQ_MSG(File file) {
        Msg m = new Msg();
        m.setMsg(file.getName());
        m.setUuid(UUID.randomUUID().toString());
        m.setType(MsgTypeEnum.TYPE_FILE_REQ);
        m.setOriginAddr(ApplicationConfig.getInstance().getChartNetWorkInterface().getInetAddress());
        return m;
    }

    public static Msg END_OF_FILE(File file) {
        Msg m = new Msg();
        m.setMsg(file.getName());
        m.setUuid(UUID.randomUUID().toString());
        m.setType(MsgTypeEnum.TYPE_FILE_REQ);
        m.setOriginAddr(ApplicationConfig.getInstance().getChartNetWorkInterface().getInetAddress());
        return m;
    }

    public byte[] serialze() {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(baos);
            oos.writeObject(this);
            oos.flush();
            byte[] byteArray = baos.toByteArray();
            byte[] bytes = Arrays.copyOf(byteArray, 1000);
            return bytes;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public static Msg deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = new ObjectInputStream(bais);
        return (Msg) ois.readObject();
    }

}
